﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Core
{
    /// <summary>
    /// 自定义数据解析器
    /// </summary>
    public class CustomDataContractResolver : DefaultContractResolver
    {
        private string[] _IgnoreMembers = new string[0];

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public CustomDataContractResolver()
        {

        }

        /// <summary>
        /// 带忽略成员集合的构造函数
        /// </summary>
        /// <param name="ignoreMembers">忽略成员集合</param>
        public CustomDataContractResolver(params string[] ignoreMembers)
            : this()
        {
            _IgnoreMembers = ignoreMembers;
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            var displayName = member.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName;
            if (!string.IsNullOrWhiteSpace(displayName))
            {
                property.PropertyName = $"{displayName}";
                property.Ignored = _IgnoreMembers.Contains(member.Name);
            }
            return property;
        }
    }
}
